package com.rem.elasticsearch.apidemo.doc;

import com.alibaba.fastjson.JSON;
import com.rem.elasticsearch.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

import static org.apache.http.HttpHost.DEFAULT_SCHEME_NAME;

/**
 * 创建单个文档
 * @author Rem
 * @date 2021-05-16
 */

@Slf4j
public class DocInsert {


    public static void main(String[] args) throws IOException {
        // 创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, DEFAULT_SCHEME_NAME)));
        // 新增文档 - 请求对象
        IndexRequest request = new IndexRequest();
        // 设置索引及唯一性标识
        request.index("user").id("1004");
        // 创建数据对象
        User user = new User("zhangsan", "女", 32);
        String userJson = JSON.toJSONString(user);
        // 添加文档数据，数据格式为 JSON 格式
        request.source(userJson, XContentType.JSON);
        // 客户端发送请求，获取响应对象
        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
        //3.打印结果信息
        System.out.println("_index:" + response.getIndex());
        System.out.println("_id:" + response.getId());
        System.out.println("_result:" + response.getResult());

        // 关闭ES客户端
        esClient.close();
    }
}
